<?php
/**
 *description:接口
 *author:李飞
 *time:2016/12/29
 */
namespace Admin\Controller;
use Think\Controller;
class PushreceiveapiController extends Controller {
	
	
	//库内调拨(单商品)
	public function distributionLog(){
		$param	=	file_get_contents("php://input");
		file_put_contents('./log/distributionLog'.date('Y-m-d',time()).'.log',date('Y-m-d H:i:s',time()).var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql
		
		 $param='[{"merchant_code":"DF1X9GN675","old_merchant_code":"TZ2591376B","old_order_no":"MG19022200002","order_no":"ERP2019022200002","goods_no":"TZ2591376B851562031304","goods_nums":"110","warehouse_code":"11330213"}]';

		$param=json_decode($param,true);
		$time=time();
		
		$warehouse_code=$param[0]['warehouse_code'];
		if(empty($warehouse_code)){
			$this->error('参数错误！');
		}
		$this->db_config($warehouse_code);
		$tranDb=M('',C('DB_PRS'),C('DB_DEPOT'));
		$tranDb->startTrans();
		
		$b=M('Books',C('DB_PRS'),C('DB_DEPOT'));
		$bc=M('BooksCate',C('DB_PRS'),C('DB_DEPOT'));
		$ao=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$g=M('Goods',C('DB_PRS'),C('DB_DEPOT'));
		
		$mv=M('DistributionLog',C('DB_PRS'),C('DB_DEPOT'));
			
		foreach($param as $key=>$value){
			
			$merchant_code=$value['merchant_code'];
			$old_merchant_code=$value['old_merchant_code'];
			$goods_no=$value['goods_no'];
			$goods_nums=$value['goods_nums'];	
			
			
			
			//原账册信息
			$old_code=$bc->where(['merchant_code'=>$old_merchant_code])->getField('code');
			//账册信息判断-begin
			$bc_info=$bc->where(['merchant_code'=>$merchant_code])->find();
			if(empty($bc_info)){
				$tranDb->rollback();
				alert_json(0,$merchant_code."仓库账册中没有此货主对应的账册信息");
			}
			//账册信息判断-end
			
			
			$old_info=$b->where(['goods_no'=>$goods_no])->find();
			if(empty($old_info)){
				$tranDb->rollback();
				alert_json(0,$goods_no."仓库账册中没有此商品编码");
			}
			
			$new_goods_no=$merchant_code.$old_info['source_no'];
			
			//账册信息下对应产品判断
			$has_b=$b->where(['goods_no'=>$new_goods_no])->count();
			
			if(!$has_b){		//不存在，则添加账册产品
				//添加账册产品
				
				$data_b=array(
								'manua_id'=>$bc_info['code'],	//货主对应账册编号
								'item_no'=>$old_info['item_no'],
								'item_type'=>$old_info['item_type'],
								'source_no'=>$old_info['source_no'],
								'goods_name'=>$old_info['goods_name'],
								'goods_no'=>$new_goods_no,	//商品编码改变
								'goods_spec'=>$old_info['goods_spec'],
								'current_type'=>$old_info['current_type'],
								'source'=>$old_info['source'],
								'unit1'=>$old_info['unit1'],
								'unit2'=>$old_info['unit2'],
								'add_time'=>$time,
								'manua_type'=>$old_info['manua_type'],
								'hs_code'=>$old_info['hs_code'],
								'status'=>1,
								'update_time'=>$time,
								'examine_time'=>$time,
								'push_arrival_time'=>$old_info['push_arrival_time'],
								'push_arrival_times'=>$old_info['push_arrival_times'],
								'old_goods_id'=>$old_info['old_goods_id'],
								'push_success_times'=>$old_info['push_success_times'],
								'sell_price'=>$old_info['sell_price'],
							);
				$res=$b->add($data_b);
				
				if(!$res){
					$tranDb->rollback();
					alert_json(0,"添加失败");
				}
			}
			
			//goods表（兼容处理）
			
			$has_g=$g->where(['goods_no'=>$new_goods_no])->count();
			if(!$has_g){
				//添加数据
				$data_g=array(
								'manua_id'=>$bc_info['code'],	//货主对应账册编号
								'item_no'=>empty($old_info['item_no'])?0:$old_info['item_no'],
								'item_type'=>empty($old_info['item_type'])?0:$old_info['item_type'],
								'source_no'=>$old_info['source_no'],
								'bar_code'=>$old_info['source_no'],
								'goods_name'=>$old_info['goods_name'],
								'goods_no'=>$merchant_code.$old_info['source_no'],	//商品编码改变
								'goods_spec'=>$old_info['goods_spec'],
								'current_type'=>$old_info['current_type'],
								'unit1'=>$old_info['unit1'],
								'unit2'=>$old_info['unit2'],
								'status'=>1,
								'goods_price'=>$old_info['sell_price'],
							);
				$res_g=$g->add($data_g);
				// echo $g->_sql();
				// die;
				
				if(!$res_g){
					$tranDb->rollback();
					alert_json(0,"添加失败");
				}
			}
			
				//调整库存-begin
				
				//减去原库存-begin
				$ao_storage=$ao->field('sum(storage_amount) storage_amount')->where(array('goods_no'=>$goods_no,'inbound_status'=>1))->select();
				$storage_amount=$ao_storage[0]['storage_amount'];//剩余库存
				if($storage_amount<$goods_nums){
					$tranDb->rollback();
					alert_json(0,$goods_no."库存不足");
				}else{
                    $rule_freez=C('base_config.rule_freez');
                    if($rule_freez){
                        $orderby="overdue_time";
                    }else{
                        $orderby="add_time";
                    }
					$ao_list=$ao->where(array('goods_no'=>$goods_no,'inbound_status'=>1,'grounding_status'=>1,'storage_amount'=>array('GT',0)))->order($orderby.' asc')->select();//按商品入库批次顺序减掉库存
					
					$amount_nums=0;//扣减库存计数
					foreach($ao_list as $kao=>$vao){
						$remain_nums=$goods_nums-$amount_nums;//剩余应扣减
						if($vao['storage_amount']>=$remain_nums){
							$data_ao=array(
								'storage_amount'=>array('exp',"storage_amount-$remain_nums"),
							 );
							 $res_ao=$ao->where(['id'=>$vao['id']])->save($data_ao);//更新原库存
							 if($res_ao===false){
								 $tranDb->rollback();
								alert_json(0,$goods_no."更新库存失败");
							 }
							 break;
						}else{
							$amount_nums+=$vao['storage_amount'];
							$data_ao=array(
								'storage_amount'=>0,
							 );
							 $res_ao=$ao->where(['id'=>$vao['id']])->save($data_ao);//更新原库存
							 if($res_ao===false){
								 $tranDb->rollback();
								alert_json(0,$goods_no."更新库存失败");
							 }
						}
					}
				}
				
				//减去原库存-end
				
				
				
					//新增库存-begin
					$data_new=[];
					$data_new=$ao->field('customs_code,erp_code,gross_weight,net_weight,wrap_type,receive_no,port,source_no,item_no,item_type,goods_name,declare_amount,total_price,price,country_code,currency,bar_code,conforming_p,nonconforming_p,scrap_one,scrap_two,storage_code,push_grounding_time,push_grounding_times,expected_time,push_arrival_time,grounding_status,arrival_time,old_goods_id,old_purchasing_no,overdue_time,confirm_status,erp_receive_amount,declare_unit,unit1,unit2,batch_no,bound_cate_code,goods_spec,goods_cate,unit2_count,area,t_arrival_time,month_rent_times,goods_tax,goods_brand,goods_marque,goods_pic,hscode')->where(['goods_no'=>$goods_no])->find();
					
					$data_new['amount']=$data_new['receive_amount']=$goods_nums;
					$data_new['goods_no']=$merchant_code.$data_new['bar_code'];
					$data_new['examine_time']=$time;
					$data_new['add_time']=$time;
					$data_new['update_time']=$time;
					$data_new['status']=1;
					$data_new['inbound_status']=1;
					
					$data_new['manual_id']=$bc_info['code'];//账册编号变更新货主
					
					$data_new['storage_amount']=$goods_nums;
					
					$res_add=$ao->add($data_new);
					if(!$res_add){
						$tranDb->rollback();
						alert_json(0,$goods_no."新增库存失败");
					}
					//新增库存-end
				
				//调整库存-end
				
				//调拨记录-begin
					$mv_data=[];
					$mv_data['old_merchant_code']=$value['old_merchant_code'];
					$mv_data['merchant_code']=$value['merchant_code'];
					$mv_data['goods_no']=$value['goods_no'];
					// $mv_data['goods_name']=$old_info['goods_name'];
					$mv_data['goods_nums']=$value['goods_nums'];
					$mv_data['storage_amount']=$value['goods_nums'];
					$mv_data['cate']=1;
					$mv_data['status']=1;
					$mv_data['examine_time']=$mv_data['add_time']=time();
					$mv_data['order_no']=$value['order_no'];
					$mv_data['old_order_no']=$value['old_order_no'];
					$res_mv=$mv->add($mv_data);
					if(!$res_mv){
						alert_json(0,"添加记录失败");
					}
				//调拨记录-end
			
		}
		$tranDb->commit();
		alert_json(1,"成功");
	}

	//接收oms推送计划入库单
	public function otherinbound(){
		$param=I('param.','','trim');
		file_put_contents('./log/get_otherinbound'.date('Y-m-d',time()).'.log',date('Y-m-d H:i:s',time()).var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql

		$warehouse_code=$param['order']['warehouse_code'];
		if(empty($warehouse_code)){
			$this->error('参数错误！');
		}
		$this->db_config($warehouse_code);
		$trans=M('',C('DB_PRS'),C('DB_DEPOT'));
		$trans->startTrans();   // 开启事务
		
		$m=M('OtherInbound',C('DB_PRS'),C('DB_DEPOT'));
		$d=M('OtherInboundInfo',C('DB_PRS'),C('DB_DEPOT'));
		$b=M('Books',C('DB_PRS'),C('DB_DEPOT'));
		$order=[];
		
		$order['order_no']=$param['order']['order_no'];
		$order['contacts_company_no']='2017';
		$order['section_no']='TZGYL-DEFAULT';
		$order['people_purchasing_no']='TZGJ0001';
		$order['people_make_no']='TZGJ0001';
		$order['add_time']=time();
		
		$has=$m->where(array('order_no'=>$order['order_no']))->count();
		if($has){
			alert_json(0,"此单已存在!");
		}
		$res=$m->add($order);
		
		if($res){
			$detail=[];
			foreach($param['detail'] as $k=>$v){
				
				$detail[$k]['order_id']=$res;
				$detail[$k]['unit_count']=$v['declare_amount'];
				$detail[$k]['price']=$v['price'];
				$source_no=$v['source_no'];
				$manua_id=substr($param['order']['owner_code'],0,9);
				$detail[$k]['books_id']=$b->where(array('source_no'=>$source_no,'left(goods_no,9)'=>$manua_id))->getField('id');
				if(empty($detail[$k]['books_id'])){
					$trans->rollback();
					alert_json(0,$source_no."账册中没有此商品编码!");
				}
			}
			
			$d_res=$d->addAll($detail);

			if(!$d_res){
				$trans->rollback();
				alert_json(0,'添加入库单详情失败');
			}else{
				$trans->commit();
				alert_json(1,'成功');
			}
		}else{
			$trans->rollback();
			alert_json(0,'添加入库单失败');
		}
	}
	//客户端订单查看接口
	public function get_pushorder(){
		$param=I('param.','','trim');
		file_put_contents('./log/get_pushorder.log',date('Y-m-d H:i:s').var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$warehouse_code=$param['warehouse_code'];
		if(empty($warehouse_code)){
			$this->error('参数错误！');
		}
		$this->db_config($warehouse_code);
		$p=M('Pushorder',C('DB_PRS'),C('DB_DEPOT'));
		$nc=M('NuclearOrder',C('DB_PRS'),C('DB_DEPOT'));
		$pa=M('Packing',C('DB_PRS'),C('DB_DEPOT'));
		
		$pa_id=$param['pa_id'];
		if(empty($pa_id)){
			$pa_id=121121;
			// $pa_id=1;
		}
		$map_pa=array();
		$map_pa['id']=array("GT",$pa_id);
		$list_pa=$pa->where($map_pa)->order('id asc')->limit(30)->select();

		$p_id=$param['p_id'];
		if(empty($p_id)){
			$p_id=1;
		}
		$nc_id=$param['nc_id'];
		if(empty($nc_id)){
			$nc_id=1;
		}
		$map_nc=array();
		$map_nc['id']=array("GT",$nc_id);
		$list_nc=$nc->where($map_nc)->order('id asc')->limit(100)->select();
		
		$map=array();
		$map['is_delivery']=0;
		$map['id']=array("GT",$p_id);
		$list_p=$p->field('id,order_no,logistics_no,is_delivery,delivery_time,times,is_emergency')->where($map)->order('id asc')->limit(30)->select();
		$list=array();
		$list['pushorder']=$list_p;
		$list['nuclear_order']=$list_nc;
		$list['packing']=$list_pa;
		
		if(empty($list_pa)){
			$arr_pa=array();
			$arr_pa[0]['id']='0';
			$arr_pa[0]['order_no']='0';
			$arr_pa[0]['logistics_no']='0';
			$arr_pa[0]['is_delivery']='0';
			$arr_pa[0]['delivery_time']='0';
			$arr_pa[0]['times']='0';
			$list['packing']=$arr_pa;
		}else{
			$list['packing']=$list_pa;
		}
		
		if(empty($list_p)){
			$arr_p=array();
			$arr_p[0]['id']='0';
			$arr_p[0]['order_no']='0';
			$arr_p[0]['logistics_no']='0';
			$arr_p[0]['is_delivery']='0';
			$arr_p[0]['delivery_time']='0';
			$arr_p[0]['times']='0';
			$arr_p[0]['is_emergency']='0';

			$list['pushorder']=$arr_p;
		}else{
			$list['pushorder']=$list_p;
		}
		if(empty($list_nc)){
			$arr_nc=array();
			$arr_nc[0]['id']='0';
			$arr_nc[0]['listing_no']='0';
			$arr_nc[0]['order_no']='0';
			$arr_nc[0]['mail_no']='0';
			$arr_nc[0]['declare_time']='0';
			$arr_nc[0]['release_time']='0';
			$arr_nc[0]['add_time']='0';
			$arr_nc[0]['status']='0';
			$arr_nc[0]['outbound_status']='0';
			$arr_nc[0]['mark']='0';
			$list['nuclear_order']=$arr_nc;
		}else{
			$list['nuclear_order']=$list_nc;
		}
		alert_json(1,$list);
	}
	//客户端订单查看接口
	public function get_packing(){
		$param=I('param.','','trim');
		file_put_contents('./log/get_pushorder.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$warehouse_code=$param['warehouse_code'];
		if(empty($warehouse_code)){
			$this->error('参数错误！');
		}
		$this->db_config($warehouse_code);
		$p=M('Packing',C('DB_PRS'),C('DB_DEPOT'));
		$time=time()-3600*24*3;
		$tdate=date("Y-m-d",$time);
		// $map['created_at']=array("gt",$tdate);
		
		$id=$param['id'];
		if(empty($id)){
			$id=1;
		}
		$map=array();
		$map['p.id']=array("GT",$id);
		$map["p.pack_weight"]=array("GT",0);
		$list=$p->alias("p")->field("p.id,p.order_no,p.all_pack_pn,p.pack_v,p.pack_weight,p.all_pack_count,p.created_at,o.logistics_no")->join("__PUSHORDER__ o on p.order_no=o.order_no","left")->where($map)->order('id asc')->limit(30)->select();
		
		if(empty($list)){
			alert_json(0,"没有数据");
		}else{
			alert_json(1,$list);
		}
	}
	//erp会员共享登录
	public function redirect_wms(){
		$param=I('param.','','trim');
		file_put_contents('./log/redirect_wms.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$warehouse_code=$param['warehouse_code'];
		if(empty($warehouse_code)){
			$this->error('参数错误！');
		}
		$this->db_config($warehouse_code);
		$w=M('Warehouse');
		$warehouse_info=$w->where(array('warehouse_code'=>$warehouse_code))->find();
		session('warehouse_code',$warehouse_info['warehouse_code']);
		session('warehouse_name',$warehouse_info['name']);
		session('warehouse_status',$warehouse_info['warehouse_status']);
		
		$Login=A('Login');
		$Login->db_config();
		$uid=M('AuthUser',C('DB_PRS'),C('DB_DEPOT'))->where($map)->find();
		// echo $w->getlastsql();
		// die;
		if(!$uid){
			$result['message']='登陆失败！用户名或密码错误。';
			$result['status']=false;
			$this->ajaxReturn($result);
		}else{
			session('personnel_no',$uid['personnel_no']);
			session('username',$uid['username']);
			$info=$w->where($map)->save($data);
			if(false===$info){
				$result['message']='更新时间和ip出错';
				$result['status']=false;
				$this->ajaxReturn($result);
			}
			session('uid',$uid['uid']);
			session('logintime',$data['lastlogintime']);

			$this->redirect('Index/index','登录成功');
		}
	}
	//云仓商品设置
	public function edit_goodscloud(){
		$datas=file_get_contents('php://input');
		$param=json_decode($datas,true);
		file_put_contents('./log/edit_goodscloud.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$warehouse_code=$param['warehouse_code'];
		$this->db_config($warehouse_code);
		$grounding_status=$param['grounding_status'];
		if($grounding_status){
			$data['cloud_unit']	=$param['cloud_unit'];
			$data['cloud_num']	=$param['cloud_num'];
			$data['cloud_depot_status']	=$param['cloud_depot_status'];
			$map['goods_no']	=$param['goods_no'];
		}else{
			$data['cloud_depot_status']	=0;
			$map['goods_no']	=$param['goods_no'];
		}
		$ao=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$res=$ao->where($map)->save($data);
		if($res!==false){
			alert_json(1,'成功');
		}else{
			alert_json(1,'失败');
		}
	}
	//拦截接口
	public function intercept_order(){
		$datas=file_get_contents('php://input');
		$param=json_decode($datas['data'],true);
		file_put_contents('./log/intercept_order.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$warehouse_code=$param['warehouse_code'];
		$this->db_config($warehouse_code);
		$data['order_no']=$param['order_no'];
		$m=M('InterceptOrder',C('DB_PRS'),C('DB_DEPOT'));
		$m_info=$m->where($data)->find();
		if(empty($m_info)){
			$res=$m->add($data);
			if($res){
				alert_json(1,'添加成功');
			}
		}else{
			alert_json(0,'订单重复');
		}
	}
	
	//批量拦截接口
	public function intercept_orders(){
		$datas=file_get_contents('php://input');
		file_put_contents('./log/intercept_orders.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		
		// $datas='{"order_no":["C201706211048497681"],"warehouse_code":"11330213"}';
		$param=json_decode($datas,true);
		
		$warehouse_code=$param['warehouse_code'];
		$this->db_config($warehouse_code);
		
		$tranDb=M('',C('DB_PRS'),C('DB_DEPOT'));
		$tranDb->startTrans();
		
		if(empty($param['order_no'])){
			$tranDb->rollback();
			alert_json(0,'没有订单');
		}
		$m=M('InterceptOrder',C('DB_PRS'),C('DB_DEPOT'));
		// dump($param['order_no']);
		// die;
		foreach($param['order_no'] as $k=>$v){
			$data=[];
			$data['order_no']=$v;
			$m_info=$m->where($data)->find();
			if(empty($m_info)){
				$res=$m->add($data);
				if(!$res){
					$tranDb->rollback();
					alert_json(0,'添加失败');
				}
			}else{
				continue;
			}
		}
		$tranDb->commit();
		alert_json(1,'添加成功');
	}
	//订单是否已同步过来
	public function has_mailno($warehouse_code,$logistics_no,$i=1){
		session_write_close();//session 文件锁
		set_time_limit(500);
		$this->db_config($warehouse_code);
		$m=M('Pushorder', C('DB_PRS'), C('DB_DEPOT'));
		$m_info=$m->where(array('logistics_no'=>$logistics_no))->find();
		if(empty($m_info)){
			sleep(20);
			$i++;
			if($i<=10){
				$this->has_mailno($warehouse_code,$logistics_no,$i);
			}
		}
	}
	//订单备注同步
	public function pushwms_mark(){
		$data=file_get_contents("php://input");
		file_put_contents('./log/pushwms_mark.log',date('Y-m-d H:i:s').$data.PHP_EOL,FILE_APPEND);//日志导出sql
		// $data='{"logistics_no":"C20170815156144","mark_mailno":"224433221","erp_code":"20"}';
		$param=json_decode($data,true);
		if(!isset($data) || count($data)==0){
            $return['status']=0;
			$return['message']='没有数据';
			$this->ajaxReturn($return);
        }
		$warehouse_code=$param['warehouse_code'];
		$this->db_config($warehouse_code);
		$m=M('Pushorder', C('DB_PRS'), C('DB_DEPOT'));
		// $this->has_mailno($warehouse_code,$param['logistics_no']);//延迟定时调用，调用的时候会卡住，所以禁用
		$m_info=$m->where(array('logistics_no'=>$param['logistics_no']))->find();
		if(empty($m_info)){
			$return['status']=0;
			$return['message']='wms没有找到对应面单数据，请稍后同步备注信息';
			$this->ajaxReturn($return);
		}
		$res=$m->where(array('logistics_no'=>$param['logistics_no']))->save(array('erp_mark_mailno'=>$param['erp_mark_mailno']));
		// echo $m->getlastsql();
		// die;
		if($res!==false){
			$return['status']=1;
			$return['message']='同步成功';
			$this->ajaxReturn($return);
		}else{
			$return['status']=0;
			$return['message']='同步失败';
			$this->ajaxReturn($return);
		}
	}
	//回调（释放）库存
	public function release_storage(){
		$datas=file_get_contents('php://input');
		// $datas='{"g_list":[{"goods_batch_no":",1264:2","goods_price":"7.75","goods_nums":"1","goods_no":"AO201706219300615055855"}],"warehouse_code":"11330213","merchant_code":"AO20170621","order_no":"P2018083000001"}';
		$param=json_decode($datas,true);
		file_put_contents('./log/release_storage.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		
		$agent_id=$param['agent_id'];
		// if(empty($agent_id)){
			// $warehouse_code='12345678';//测试仓库编码
			// $warehouse_code='11330213';
		// }else{
			$warehouse_code=$param['warehouse_code'];
			$order_no=$param['order_no'];
			$merchant_code=$param['merchant_code'];
			if(empty($warehouse_code)){
				$return['status']=0;
				$return['message']="没有仓库编码";
				$this->ajaxReturn($return);
			}
			if(strpos($order_no,"-bak")){
                $return['status']=0;
                $return['message']="此订单已经处理过了";
                $this->ajaxReturn($return);
            }
			if(empty($order_no)){
				$return['status']=0;
				$return['message']="没有订单号";
				$this->ajaxReturn($return);
			}
			if(empty($merchant_code)){
				$return['status']=0;
				$return['message']="没有货主编码";
				$this->ajaxReturn($return);
			}
		// }
		$g_list=$param['g_list'];
		$this->db_config($warehouse_code);
		$trans=M('',C('DB_PRS'),C('DB_DEPOT'));
		$trans->startTrans();   // 开启事务
		$ao=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$rs=M('ReleaseStorage',C('DB_PRS'),C('DB_DEPOT'));
		// dump($g_list);
		// die;
		$has=$rs->where(['merchant_code'=>$merchant_code,'order_no'=>$order_no])->count();
		if($has){
			$trans->rollback();
			$return['status']=0;
			$return['message']="此订单已操作过了";
			$this->ajaxReturn($return);
		}
		foreach($g_list as $k=>$v){
			$goods_batch_no=substr($v['goods_batch_no'],1);
			$goods_list=explode(',',$goods_batch_no);
			foreach($goods_list as $ks=>$vs){
				$goods_info=explode(':',$vs);
				$map['id']=$goods_info[0];
				$ao_info=$ao->where($map)->find();
				if(empty($ao_info)){
					$trans->rollback();
					$return['status']=0;
					$return['message']="没有此数据";
					$this->ajaxReturn($return);
				}
				$data['freez_amount']=array('exp','freez_amount-'.$goods_info[1]);
				$data['storage_amount']=array('exp','storage_amount+'.$goods_info[1]);
				$res=$ao->where($map)->save($data);
				// echo $ao->getlastsql();
				// die;
				if($res===false){
					$trans->rollback();
					$return['status']=0;
					$return['message']="失败";
					$this->ajaxReturn($return);
				}else{
					//添加回调记录
					$rs_data=[];
					$rs_data['goods_id']=$goods_info[0];
					$rs_data['goods_nums']=$goods_info[1];
					$rs_data['goods_no']=$ao_info['goods_no'];
					$rs_data['goods_name']=$ao_info['goods_name'];
					$rs_data['order_no']=$order_no;
					$rs_data['merchant_code']=$merchant_code;
					$rs_data['add_time']=time();
					
					$res_rs=$rs->add($rs_data);
					
					if(!$res_rs){
						$trans->rollback();
						$return['status']=0;
						$return['message']="添加回调库存记录失败";
						$this->ajaxReturn($return);
					}
				}
			}
		}
		$trans->commit();
		$return['status']=1;
		$return['message']="成功";
		$this->ajaxReturn($return);
	}
	
	//按批次号冻结库存
	//ao_info批次详情
	//vs订单商品详情
	//自动关联批次库存
	public function freez_storage(){
		$datas=file_get_contents('php://input');
		$param=json_decode($datas,true);
		file_put_contents('./log/freezstorage/freez_storage'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$warehouse_code=$param['warehouse_code'];
		$agent_id=$param['agent_id'];

		$this->db_config($warehouse_code);
		$trans=M('',C('DB_PRS'),C('DB_DEPOT'));
		$trans->startTrans();   // 开启事务
		foreach($param['detail'] as $ks=>$vs){
			if(empty($agent_id)){
				$res=freez_storage_erp($vs);
			}else{
				$res=freez_storage_erp($vs,1,'',$agent_id);
			}
			if(!$res['status']){
				$trans->rollback();
				$this->ajaxReturn($res);
			}else{
				$return['detail'][]=$res['detail'];
			}
		}
		$return['status']=1;
		$return['message']='扣库存成功！';
		$trans->commit();
		$this->ajaxReturn($return);
	}
	//库存更新(按批次)
	//status:1-冻结2-出库3-退库
	public function update_goodsamount(){
		$data=I('param.','','trim');
		file_put_contents('./log/update_goodsamount'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		if(empty($data)){
			$return['status']=0;
			$return['info']="没有传输数据";
			$this->ajaxReturn($return);
		}
		$ss=$data['data'];
		$param=json_decode($ss,true);
		$warehouse_code=$param['warehouse_code'];
		
		$status=$param['status'];
		$amount=$param['amount'];
		$id=$param['id'];
		$cloud_status=$param['cloud_status'];//是否云仓商品
		if(empty($id)){
			$return['status']=0;
			$return['info']="没有传输入库批次id";
			$this->ajaxReturn($return);
		}
		if(empty($warehouse_code)){
			$return['status']=0;
			$return['info']="没有传输仓库编码";
			$this->ajaxReturn($return);
		}
		if(empty($status)){
			$return['status']=0;
			$return['info']="没有传输更新状态参数";
			$this->ajaxReturn($return);
		}
		if(empty($amount)){
			$return['status']=0;
			$return['info']="没有传输数量";
			$this->ajaxReturn($return);
		}
		// $warehouse_code='12345678';//测试仓库编码
		$this->db_config($warehouse_code);
		$ao=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		if($status==1){//当前操作为冻结状态
			$data_ao['freez_amount']=array('exp','freez_amount+'.$amount);//冻结数量
			$data_ao['storage_amount']=array('exp','storage_amount-'.$amount);//更新库存
			if(empty($cloud_status)){
				$data_ao['cloud_freez_num']=array('exp','cloud_freez_num+'.$amount);//冻结云仓数量
				$data_ao['cloud_storage_num']=array('exp','cloud_storage_num-'.$amount);//更新云仓库存
			}
		}
		if($status==2){//当前操作为出库状态
			$data_ao['freez_amount']=array('exp','freez_amount-'.$amount);//冻结数量
			if(empty($cloud_status)){
				$data_ao['cloud_freez_num']=array('exp','cloud_freez_num-'.$amount);//冻结数量
			}
		}
		if($status==3){//当前操作为退库状态
			$data_ao['freez_amount']=array('exp','freez_amount-'.$amount);//冻结数量
			$data_ao['storage_amount']=array('exp','storage_amount+'.$amount);//更新库存
			if(empty($cloud_status)){
				$data_ao['cloud_freez_num']=array('exp','cloud_freez_num-'.$amount);//冻结数量
				$data_ao['cloud_storage_num']=array('exp','cloud_storage_num+'.$amount);//更新库存
			}
		}

		$map_ao['id']=$id;//条件
		$res_ao=$ao->where($map_ao)->save($data_ao);//更新
		if($res_ao){
			$return['status']=1;
			$return['info']="更新成功";
			$this->ajaxReturn($return);
		}else{
			$return['status']=0;
			$return['info']="更新批次库存失败";
			$this->ajaxReturn($return);
		}
	}
	
	//订单信息接口--接收
    public function pushorder(){
		$data=I('param.','','trim');
		file_put_contents('./log/data'.date('Y-m-d').'.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		if(empty($data)){
			$return['status']=0;
			$return['info']="没有数据";
			$this->ajaxReturn($return);
		}
		 $ss=$data['data'];
		 $param=json_decode($ss,true);
		 $warehouse_code=$param['warehouse_code'];
		 // $warehouse_code='12345678';//测试仓库编码
		 if(!empty($param['send_info'])){
			 $send_info=$param['send_info'];
		 }
		 $this->db_config($warehouse_code);
		 $m=M('Pushorder','tz_',C('DB_DEPOT'));
		 $g=M('Pushordergoods','tz_',C('DB_DEPOT'));
		 $p=M('Printorder','tz_',C('DB_DEPOT'));
		 $ao=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));

		 $order_total=0;//初始化订单数
		 $duplicate=0;//初始化重复订单数
		 foreach($param['info'] as $key=>$value){
			 if(empty($value['order_no'])){
				 $return['status']=0;
				 $return['info']="订单编号不能为空";
				 $this->ajaxReturn($return);
			 }
			 $order_info=$m->where(array('order_no'=>$value['order_no']))->find();//判断是否是重复订单号
			 if($order_info){
				 $param['order_total']=$param['order_total']-1;
				 $duplicate++;
				 continue;
			 }
			 $add_data=array();
			 
			 if(!empty($value['old_order_no'])){
				 $add_data['old_order_no']	=$value['old_order_no'];
			 }
			 $add_data['order_no']		=$value['order_no'];
			 $add_data['user_name']		=$value['user_name'];
			 $add_data['user_phone']	=$value['user_phone'];
			 $add_data['user_idcard']	=$value['user_idcard'];
			 $add_data['province']		=$value['province'];
			 $add_data['city']			=$value['city'];
			 $add_data['area']			=$value['area'];
			 $add_data['user_address']	=$value['user_address'];
			 if(!empty($value['is_emergency'])){
				 $add_data['is_emergency']	=$value['is_emergency'];
			 }
			 
			 $add_data['logistics_no']	=$value['logistics_no'];
			 if(!empty($value['logiscompany_name'])){
				 $add_data['logiscompany_name']	=$value['logiscompany_name'];//物流公司名称
			 }
			 if(!empty($value['logiscompany_code'])){
				 $add_data['logistics_business']	=$value['logiscompany_code'];//物流公司编码
			 }
			 if(!empty($value['logistics_business'])){
				 $add_data['logistics_business']	=$value['logistics_business'];//物流公司编码
			 }
			 if(!empty($value['erp_code'])){
				 $add_data['erp_code']	=$value['erp_code'];
			 }
			 if(!empty($value['remark'])){
				 $add_data['erp_mark_mailno']=$value['remark'];
			 }

			 $add_data['platform_name']		=$value['platform_name'];
			 $add_data['company_name']		=$value['company_name'];
			 
			 if(!empty($value['order_cate'])){
				 $add_data['order_cate']	=$value['order_cate'];
			 }
			 if(!empty($value['transport_cate'])){
				 $add_data['transport_cate']	=$value['transport_cate'];
			 }
			 if(!empty($value['delivery_code'])){
				 $add_data['delivery_code']		=$value['delivery_code'];
			 }
			 
			 if(!empty($value['shipping_list_attribute_money'])){
				 $add_data['shipping_list_attribute_money']		=$value['shipping_list_attribute_money'];
			 }
			 //特殊业务代码(BEST-FREIGHT:货到付款、BEST-COD：代收 货款)
			 if(!empty($value['shipping_list_attribute_code'])){
				 $add_data['shipping_list_attribute_code']		=$value['shipping_list_attribute_code'];
			 }
			 
			 // if(!empty($value['cod_money'])){
				 $add_data['cod_money']		=$value['cod_money'];
			 // }
			 
			 //总价格
			 $add_data['total_price']=$value['order_amount'];
			 
			 $add_data['add_time']		=time();
			 $add_id=$m->add($add_data);//订单添加

			$order_id=$add_id;
			if($add_id){
				$order_total++;
				$add_ids[]=$add_id;//记录插入订单的id值
				foreach($value['order_detail'] as $k => $v){
					// $ao_info=$ao->where(array('batch_no'=>$v['goods_batch_no'],'goods_no'=>$v['goods_sn']))->find();//获取批次详情
					$continue_s=0;
					//云集订单bug修改方案(去除一个订单中相同商品分开显示的问题)-begin
					$g_list=$g->where(array('order_id'=>$order_id))->select();
					foreach($g_list as $ks=>$vs){
						 if($vs['goods_no']==$v['goods_sn']){
							 $datasss['goods_nums']=array('exp','goods_nums+'.$v['goods_nums']);
							 // if(!empty($v['order_cate'])){//兼容销售订单中添加商品时按批次来添加
								// if($v['order_cate']==2){//2为销售订单
									// $datas['goods_batch_no'].=",".$ao_info['id'].":".$v['goods_nums'];
								// }
							 // }
							 $resss=$g->where(array('order_id'=>$order_id,'goods_no'=>$vs['goods_no']))->save($datasss);//商品数量叠加
							 // dump($resss);
							 // echo $g->getlastsql();
							 if($resss!==false){
								 $continue_s=1;
							 }
						 }
					}
					if($continue_s==1){
						 continue;
					}
					 //云集订单bug修改方案(去除一个订单中相同商品分开显示的问题)-end
					 $datas=array();
					 $datas['goods_nums']=$v['goods_nums'];
					 $datas['goods_name']=$v['goods_name'];
					 $datas['goods_no']=$v['goods_sn'];
					 $datas['spec']=$v['spec'];
					 $datas['goods_unit']=$v['goods_unit'];
					 $datas['source']=$v['source'];
					 $datas['hs_code']=$v['hs_code'];
					 // $datas['goods_batch_no']=$ao_info['id'].":".$v['goods_nums'];
					 $datas['goods_batch_no']=$v['goods_batch_no'];//澳洲erp自动下单，已冻结批次库存信息

					 if(empty($v['goods_sn'])){
						 $datas['bar_code']=$v['goods_sn'];
					 }else{
						 $datas['bar_code']=$v['bar_code'];
					 }
					 
					 $datas['order_id']=$order_id;

					 $res=$g->add($datas);//订单详情添加
					 // echo $g->getlastsql();
					 file_put_contents('./log/push_ordergoods'.date('Y-m-d').'.log',date('Y-m-d H:i:s').$g->getlastsql().PHP_EOL,FILE_APPEND);//日志导出sql
					 if($res){
						 continue;
					 }else{
						 $m->where(array('id'=>array('in',$add_ids)))->delete();//回滚操作
						 $return['status']=0;
						 $return['info']='订单编号'.$value['order_no'].'|商品编码'.$v['goods_sn']."添加详情出错";
						 $this->ajaxReturn($return);
					 }
				 }
				 //面单信息添加
				 //file_put_contents('.//log/Printorder.log',date('Y-m-d H:i:s').var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql
				$print_order=array();
				$print_order['destcode']=$value['destcode'];//大笔头（目的地）
				$print_order['billProvideSiteName']=$value['bill_provide_site_name'];//运单发放站点
				$print_order['billProvideSiteCode']=$value['bill_provide_site_code'];//运单发放站点编码
				$print_order['markDestination']=$value['destcode'];//大笔头
				$print_order['pkgCode']=$value['pkgCode'];//集包编码
				$print_order['origincode']=$value['origincode'];//发件地

				 if(!empty($value['logiscompany_name'])){
					 $print_order['logiscompany_name']	=$value['logiscompany_name'];//物流公司名称
				 }
				 if(!empty($value['logiscompany_code'])){
					 $print_order['logistics_business']	=$value['logiscompany_code'];//物流公司编码
				 }
				 if(!empty($value['logistics_business'])){
					 $print_order['logistics_business']	=$value['logistics_business'];//物流公司编码
				 }
				
				if(!empty($value['sorting_code'])){
					$print_order['sortingCode']		=$value['sorting_code'];
				}
			 
				$print_order['receiveMan']=$value['user_name'];
				$print_order['receiveManPhone']=$value['user_phone'];
				$print_order['receiveProvince']=$value['province'];
				$print_order['receiveCity']=$value['city'];
				$print_order['receiveCounty']=$value['area'];
				$print_order['receiveManAddress']=$value['user_address'];
				if(!empty($param['send_info'])){
					$print_order['custid']=$send_info['custid'];
					$print_order['pay_methods']=$send_info['pay_methods'];
					$print_order['sendMan']=$send_info['sendman'];
					$print_order['sendManPhone']=$send_info['sendmanphone'];
					$print_order['sendManAddress']=$send_info['sendmanaddress'];
					$print_order['sendPostcode']=$send_info['sendpostcode'];
					$print_order['sendProvince']=$send_info['sendprovince'];
					$print_order['sendCity']=$send_info['sendcity'];
					$print_order['sendCounty']=$send_info['sendcounty'];
				}
				$print_order['txLogisticID']=$value['order_no'];//订单号
				$print_order['mailNo']=$value['logistics_no'];//面单号
				$print_order['add_time']=time();//添加时间
				$print_order['order_no']=$value['order_no'];//订单号
				$stat=$p->add($print_order);
				// echo $p->getlastsql();
				// die;
				// file_put_contents('./log/Printorder.log',date('Y-m-d H:i:s').$p->_sql().PHP_EOL,FILE_APPEND);//日志导出sql
				 if($stat){
					 continue;
				 }else{
					 $m->where(array('id'=>array('in',$add_ids)))->delete();//回滚操作
					 $return['status']=0;
					 $return['info']='订单编号'.$value['order_no'].'|商品编码'.$v['goods_sn']."添加面单详情出错";
					 $this->ajaxReturn($return);
				 }
			 }else{
				 if(!empty($add_ids)){
					 $m->where(array('id'=>array('in',$add_ids)))->delete();//回滚操作
				 }
				 // echo $m->getlastsql();
				 continue;//忽略错误，继续执行
				 // $return['status']=0;
				 // $return['info']='订单编号'.$value['order_no']."添加出错";
				 // $this->ajaxReturn($return);
			 } 
		 }
		 if($order_total==$param['order_total']){
			 $return['status']=1;
			 $return['info']="添加成功".$order_total."条，重复".$duplicate."条";
			 $return['new_order_total']=$order_total;
			 $return['duplicate_total']=$duplicate;
			 $return['old_order_total']=$param['order_total'];
			 $this->ajaxReturn($return);
		 }else{
			 $m->where(array('id'=>array('in',$add_ids)))->delete();//回滚操作
			 $return['status']=0;
			 $return['info']="添加失败,推送数量与接收后插入数量不一致";
			 $return['new_order_total']=$order_total;
			 $return['old_order_total']=$param['order_total'];
			 $this->ajaxReturn($return);
		 }
	}
	//计划入库信息接口--(跨境)
    public function planreceipt(){
		 $data=I('param.','','trim');
		 file_put_contents('./log/planreceipt.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		 $ss=$data['data'];
		 $param=json_decode($ss,true);
		 
		 $warehouse_code=$param['warehouse_code'];
		 // $warehouse_code='12345678';//测试仓库编码
		 $this->db_config($warehouse_code);
		 // dump(C('DB_DEPOT'));
		 // die;
		 $m=M('ArrivalOrderPlan',C('DB_PRS'),C('DB_DEPOT'));
		 $n=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		 $b=M('Books',C('DB_PRS'),C('DB_DEPOT'));

		 $stat=$m->where(array('old_order_no'=>$param['plan_info']['plan_receipts_id']))->find();
		 
		 if($stat){
			$return['status']=2;
			$return['info']='数据重复，已推';
			$this->ajaxReturn($return);
		 }
		 $t_no=$this->serialNumber('ArrivalOrderPlan',$warehouse_code);//流水号
		 $order_no='AO'.date('Ymd',time()).$t_no;//流水单号
		 $batch_no='BAO'.date('YmdHis',time());//批次号
		 $data_info['order_no']	=$order_no;
		 $data_info['batch_no']=$batch_no;
		 $data_info['old_order_no']	=$param['plan_info']['plan_receipts_id'];
		 $data_info['manual_id']	=$param['plan_info']['manual_id'];
		 // $data_info['manual_id']	='AO201706211413';
		 $data_info['customs_code']=$param['plan_info']['customs_code'];
		 $data_info['gross_weight']=$param['plan_info']['gross_weight'];
		 $data_info['net_weight']=$param['plan_info']['net_weight'];
		 $data_info['amount']=$param['plan_info']['amount'];
		 $data_info['wrap_type']=$param['plan_info']['wrap_type'];
		 $data_info['receive_no']=$param['plan_info']['receive_no'];
		 $data_info['port']=$param['plan_info']['port'];
		 $data_info['print_status']=$param['plan_info']['print_status'];
		 // $data_info['receive_apply_status']=$param['plan_info']['receive_apply_status'];
		 // $data_info['plan_apply_status']=$param['plan_info']['plan_apply_status'];
		$data_info['plan_print_status']=$param['plan_info']['plan_print_status'];
		$data_info['old_add_time']=$param['plan_info']['add_time'];
		
		$owner_code=$param['plan_info']['owner_code'];//货主编码
		
		$data_info['add_time']=time();
		 
		$status=$m->add($data_info);

		file_put_contents('./log/PlanReceipt.log',date('Y-m-d H:i:s').$m->_sql().PHP_EOL,FILE_APPEND);//日志导出sql
		if($status){
			$a=0;
			$count=count($param['plan_detail_info']);
			foreach($param['plan_detail_info'] as $k => $v){	//计划入库信息详情接口
				$goods_no=$owner_code.$v['source_no'];//商品编码=货主编码+条形码（料号）
				$data_info_clild=array();
				$data_info_clild['order_no']=$order_no;
				$data_info_clild['batch_no']=$batch_no;
				$data_info_clild['plan_id']=$status;
				$data_info_clild['old_goods_id']	=$v['merge_goods_id'];
				$data_info_clild['old_purchasing_no']=$v['plan_receipts_id'];
				
				// $data_info_clild['manual_id']		=$param['plan_info']['manual_id'];
				// $data_info_clild['manual_id']		='AO201706211413';
				$books_info=$b->where(array('goods_no'=>$goods_no))->find();
				if(empty($books_info)){
					$res=$m->where(array('order_no'=>$order_no))->delete();//回滚操作
					$res=$n->where(array('order_no'=>$order_no))->delete();//回滚操作
					$return['status']=0;
					$return['info']='料号['.$v['source_no'].']账册中没有找到对应的商品';
					$this->ajaxReturn($return);
				}
				$data_info_clild['manual_id']=$books_info['manua_id'];
				
				$data_info_clild['source_no']		=$v['source_no'];
				$data_info_clild['item_no']			=$v['item_no'];
				$data_info_clild['item_type']		=$v['item_type'];
				$data_info_clild['goods_no']		=$goods_no;
				$data_info_clild['hscode']			=$v['hs_code'];
				$data_info_clild['goods_name']		=$v['goods_name'];
				$data_info_clild['declare_amount']	=$v['declare_amount'];
				$data_info_clild['total_price']		=$v['total_price'];
				$data_info_clild['price']			=$v['price'];
				$data_info_clild['declare_unit']	=$v['declare_unit'];
				$data_info_clild['unit1']	=$v['unit1'];
				$data_info_clild['status']	=1;
				
				$data_info_clild['country_code']	=$v['country_code'];
				$data_info_clild['currency']		=$v['currency'];
				$data_info_clild['bar_code']		=$v['bar_code'];
				$data_info_clild['add_time']		=$v['add_time'];
				$statuss=$n->add($data_info_clild);
				 // echo $n->getlastsql();
				 file_put_contents('./log/PlanReceiptsDetail.log',date('Y-m-d H:i:s').$m->_sql().PHP_EOL,FILE_APPEND);//日志导出sql
				 if($statuss){
					 $a=$a+1;
					 continue;
				 }else{
					 // echo $n->getlastsql();
					$res=$m->where(array('order_no'=>$order_no))->delete();//回滚操作
					$res=$n->where(array('order_no'=>$order_no))->delete();//回滚操作
					// dump($v['order_no']);
					$return['status']=0;
					$return['info']='料号['.$v['source_no'].']添加失败';
					$this->ajaxReturn($return);
				 }
			 }
			 if($a==$count){
				 $return['status']=1;
				 $return['info']='添加成功';
				 $this->ajaxReturn($return);
			 }
		 }
	}
	//账册详细产品信息--接收
	public function booksinfoOrder_new(){
		
		$datas=html_entity_decode(I('data'));
				
		file_put_contents('./log/booksinfoOrder.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		
		// $datas='{"identity":{"sign":"971c0d310abb31b43d21b6c50adb03e6","timestamp":1536053836},"data":{"erp_code":82,"warehouse_code":"11330213","list":{"id":162,"manua_id":40,"goods_name":"u6d4bu8bd52","goods_no":"1231313","unit1":3,"unit2":"","goods_spec":"1000KG/u4e2a","coin_code":326,"country_code":"112","source_no":"121231223","hs_code":"1231231222","item_no":"","item_type":"","sell_price":"120000.00"}}}';
		
		$tdata=json_decode($datas,true);
		$param=$tdata['data'];
		
		$warehouse_code=$param['warehouse_code'];
		
		$data['manua_id']	=$param['list']['manua_id'];
		$data['goods_name']	=$param['list']['goods_name'];
		$data['goods_no']	=$param['list']['goods_no'];
		$data['unit1']	=$param['list']['unit1'];
		$data['unit2']	=$param['list']['unit2'];
		// $data['price']	=$param['list']['price'];
		$data['goods_spec']	=$param['list']['goods_spec'];
		$data['current_type']=$param['list']['coin_code'];
		$data['source']		=$param['list']['country_code'];
		$data['source_no']	=$param['list']['source_no'];
		$data['hs_code']	=$param['list']['hs_code'];
		$data['item_no']	=$param['list']['item_no'];
		$data['item_type']	=$param['list']['item_type'];
		$data['old_goods_id']	=$param['list']['id'];
		$data['sell_price']	=$param['list']['sell_price'];
		$data['add_time']	=time();
		$data['status']=0;
		$erp_code=$param['erp_code'];

		$this->db_config($warehouse_code);
		$m=M('Books',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('BooksCate',C('DB_PRS'),C('DB_DEPOT'));
		$res=$n->where(array('code'=>$param['list']['manua_id'],'erp_code'=>$erp_code))->find();

		if($res){
			$info=$m->where(array('manua_id'=>$param['list']['manua_id'],'goods_no'=>$param['list']['goods_no']))->find();
			if($info){//存在则修改数据
				// $map_b['old_goods_id']=$param['product_id'];
				$map_b['goods_no']=$data['goods_no'];
				$map_b['manua_id']=$data['manua_id'];
				$status=$m->where($map_b)->save($data);
				// echo M('Books',C('DB_PRS'),C('DB_DEPOT'))->_sql();
				// die;
				file_put_contents('./log/booksinfoOrder.log',date('Y-m-d H:i:s').var_export($status,true).PHP_EOL,FILE_APPEND);//日志导出sql
				if($status!==false){
					$return['status']=1;
					$return['info']="修改成功";
					$this->ajaxReturn($return);
				}else{
					$return['status']=0;
					$return['info']="修改失败";
					$this->ajaxReturn($return);
				}
			}else{
				$status=M('Books',C('DB_PRS'),C('DB_DEPOT'))->add($data);//到货通知单添加
				//echo M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql();
				if($status){
					$return['status']=1;
					$return['info']="添加成功";
					$this->ajaxReturn($return);
				}else{
					$return['status']=0;
					$return['info']="添加失败";
					$this->ajaxReturn($return);
				}
			}
		}else{
			$return['status']=2;
			$return['info']="没有此账册编码";
			$this->ajaxReturn($return);
		}
		
	}
	//账册详细产品信息--接收
    public function booksinfoOrder(){
		$datas=file_get_contents('php://input');
		// $datas='{"product_id":"1433","twice":1,"erp_code":"23","warehouse_code":"11330213","list":{"id":"198","name":"MRO \\u6574\\u4e32\\u8461\\u8404\\u5e72\\u6563\\u88c5\\u5927\\u5305\\u88c5 \\u9633\\u5149\\u73ab\\u7470\\u9999 4kg","count":null,"count_t":null,"price":"68.00","price_t":null,"unit":"\\u767e\\u526f","unit_no":"040","unit_t":null,"unit_t_goods_spec":"NaN","unit_no_t":null,"sn":"9343925000245","goods_no":"AO201706219343925000245","hs_code":"2006009090","pn":"9343925000245","standard":"4Kg\\/\\u888b","currency":"\\u6fb3\\u5927\\u5229\\u4e9a\\u5143","country":"\\u6fb3\\u5927\\u5229\\u4e9a","zccode":"AO201706211413","category":"0","examined":"2","created_at":"2017-12-27 13:05:02","country_code":"601","coin_code":"601","material_price":null,"scrap_price":"1.00","goods_cate":"1","rule_code":null,"factory_rule_name":null,"factory_rule_code":null,"level_rule_name":null,"level_rule_code":null,"item_type":"0","item_no":"85","net_weight":"4.00000","gross_weight":"4.80000","goods_tax":"0.11900","sell_price":"12.00","warehouse_code":"11330213","purchase_price":"10.0000","tariff_rate":"0.0000","consumption_rate":"0.0000","increment_rate":"0.1700","discount_rate":"0.7000"}}';
		
		file_put_contents('./log/booksinfoOrder.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$param=json_decode($datas,true);
		$warehouse_code=$param['warehouse_code'];
		$twice=$param['twice'];
		$data['manua_id']	=$param['list']['zccode'];
		$data['goods_name']	=$param['list']['name'];
		$data['goods_no']	=$param['list']['goods_no'];
		$data['unit1']	=$param['list']['unit_no'];
		$data['unit2']	=$param['list']['unit_no_t'];
		// $data['price']	=$param['list']['price'];
		$data['goods_spec']	=$param['list']['standard'];
		$data['current_type']=$param['list']['coin_code'];
		$data['source']		=$param['list']['country_code'];
		$data['source_no']	=$param['list']['pn'];
		$data['hs_code']	=$param['list']['hs_code'];
		$data['item_no']	=$param['list']['item_no'];
		$data['item_type']	=$param['list']['item_type'];
		$data['old_goods_id']	=$param['list']['id'];
		$data['sell_price']	=$param['list']['sell_price'];
		$data['add_time']	=time();
		$data['status']=0;
		$erp_code=$param['erp_code'];

		$this->db_config($warehouse_code);
		$m=M('Books',C('DB_PRS'),C('DB_DEPOT'));
		$n=M('BooksCate',C('DB_PRS'),C('DB_DEPOT'));
		$res=$n->where(array('code'=>$param['list']['zccode'],'erp_code'=>$erp_code))->find();

		if($res){
			if($twice==1){//二次推送，则修改账册内容
				// $map_b['old_goods_id']=$param['product_id'];
				$map_b['goods_no']=$data['goods_no'];
				$map_b['manua_id']=$data['manua_id'];
				$status=M('Books',C('DB_PRS'),C('DB_DEPOT'))->where($map_b)->save($data);
				// echo M('Books',C('DB_PRS'),C('DB_DEPOT'))->_sql();
				// die;
				if($status!==false){
					$return['status']=1;
					$return['info']="修改成功";
					$this->ajaxReturn($return);
				}else{
					$return['status']=0;
					$return['info']="修改失败";
					$this->ajaxReturn($return);
				}
			}else{
				$status=M('Books',C('DB_PRS'),C('DB_DEPOT'))->add($data);//到货通知单添加
				//echo M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql();
				if($status){
					$return['status']=1;
					$return['info']="添加成功";
					$this->ajaxReturn($return);
				}else{
					$return['status']=0;
					$return['info']="添加失败";
					$this->ajaxReturn($return);
				}
			}
		}else{
			$return['status']=2;
			$return['info']="没有此账册编码";
			$this->ajaxReturn($return);
		}
		
	}
	//账册申请信息--接收
	public function booksOrder_new(){
		$datas=html_entity_decode(I('data'));
		file_put_contents('./log/booksOrder.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		file_put_contents('./log/booksOrder.log',date('Y-m-d H:i:s').var_export(strlen($datas),true).PHP_EOL,FILE_APPEND);//日志导出sql

		// $ss='{"identity":{"sign":"2d1de4843cafdb17f771116fed61f186","timestamp":1536051992},"data":{"erp_code":"82","warehouse_code":"11330213","list":{"id":40,"name":"账册-测试1","type":2,"book_no":40,"merchant_code":"82"}}}';
		// var_dump($ss);
		// die;
		
		$tdata=json_decode($datas,true);
		
		file_put_contents('./log/booksOrder.log',date('Y-m-d H:i:s').var_export($tdata,true).PHP_EOL,FILE_APPEND);//日志导出sql

		$param=$tdata['data'];
		
		$warehouse_code		=$param['warehouse_code'];
		$data['name']		=$param['list']['name'];
		$data['erp_code']	=$param['erp_code'];
		$data['cate']		=$param['list']['type'];
		$data['code']		=$param['list']['book_no'];
		$data['merchant_code']=$param['list']['merchant_code'];
		$data['old_books_id']=$param['list']['id'];
		$data['add_time']	=time();
		
		$where['code']=$param['list']['book_no'];
		$where['erp_code']=$param['erp_code'];
		
		$this->db_config($warehouse_code);
		$m=M('BooksCate',C('DB_PRS'),C('DB_DEPOT'));

		$info=$m->where($where)->find();
		if($info){
			unset($data['add_time']);
			$data['status']=0;
			$status=$m->where($where)->save($data);
			if($status!==false){
				$return['status']=1;
				$return['info']="更新成功";
				$this->ajaxReturn($return);
			}else{
				$return['status']=0;
				$return['info']="更新失败";
				$this->ajaxReturn($return);
			}
		}else{
			$status=$m->add($data);//添加
			if($status){
				$return['status']=1;
				$return['info']="成功";
				$this->ajaxReturn($return);
			}else{
				$return['status']=0;
				$return['info']="失败";
				$this->ajaxReturn($return);
			}
		}
	}
	//账册申请信息--接收
    public function booksOrder(){
		$datas=file_get_contents('php://input');
		file_put_contents('./log/booksOrder.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		// $datas='{"erp_code":"1","warehouse_code":"11246","list":{"id":"2","name":"\\u70ed\\u7279\\u8ba9\\u4ed6","book_no":"43534534","type":"2","operator":"17764505876","created_at":"2017-02-06 15:48:05","erp_code":"1"}}';
		$param=json_decode($datas,true);
		// dump($param);
		
		$warehouse_code		=$param['warehouse_code'];
		$data['name']		=$param['list']['name'];
		$data['erp_code']	=$param['erp_code'];
		$data['cate']		=$param['list']['type'];
		$data['code']		=$param['list']['book_no'];
		$data['merchant_code']=$param['list']['merchant_code'];
		$data['old_books_id']=$param['list']['id'];
		$data['add_time']	=time();
		
		$where['code']=$param['list']['book_no'];
		$where['erp_code']=$param['erp_code'];
		// dump($data);
		$this->db_config($warehouse_code);
		$m=M('BooksCate',C('DB_PRS'),C('DB_DEPOT'));
		$e=M('Erp',C('DB_PRS'),C('DB_DEPOT'));
		$erp_info=$e->where(array('code'=>$param['erp_code']))->find();

		if(empty($erp_info)){
			$return['status']=0;
			$return['info']="系统中未找到erp_code对应的企业信息，请通知对方添加后再推送！";
			$this->ajaxReturn($return);
		}
		$info=$m->where($where)->find();
		if($info){
			unset($data['add_time']);
			$data['status']=0;
			$status=$m->where($where)->save($data);
			if($status!==false){
				$return['status']=1;
				$return['info']="推送成功";
				$this->ajaxReturn($return);
			}else{
				$return['status']=0;
				$return['info']="推送失败";
				$this->ajaxReturn($return);
			}
		}else{
			$status=$m->add($data);//添加
			if($status){
				$return['status']=1;
				$return['info']="推送成功";
				$this->ajaxReturn($return);
			}else{
				$return['status']=0;
				$return['info']="推送失败";
				$this->ajaxReturn($return);
			}
		}
		
	}
	//到货通知单接口--接收
	public function arrivalOrder_erp(){
			$data=file_get_contents('php://input');
			file_put_contents('./log/arrivalOrder_data.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql

			$param=json_decode($data,true);
			
			$value=$param['data'];
			$warehouse_code=$value['list']['warehouse_code'];
			$this->db_config($warehouse_code);
			$country=M('Country',C('DB_PRS'),C('DB_DEPOT'));
			$trans=M('',C('DB_PRS'),C('DB_DEPOT'));
			$trans->startTrans();   // 开启事务
			$coin=M('Coin',C('DB_PRS'),C('DB_DEPOT'));
			
		
			$t_no=$this->serialNumber_arrivalOrder('ArrivalOrder',$warehouse_code);//流水号
			$order_no='AO'.date('Ymd',time()).$t_no;//流水单号
			$batch_no='BAO'.date('YmdHis',time());//批次号
			
			$list=array();
			$list['order_no']=$order_no;
			$list['batch_no']=$batch_no;
			
			foreach($value['list']['goods'] as $k => $v){
				
				$country_info=$country->where(array('country_name'=>$v['country']))->find();
				$coin_info=$coin->where(array('coin_name'=>$v['currency']))->find();
				
				$list['old_purchasing_no']=$value['list']['order_no'];
				$list['currency']=$coin_info['coin_code'];
				$list['bar_code']=$v['sn'];//条形码
				$list['old_goods_id']=$v['goods_id'];
				$list['country_code']=$country_info['country_code'];
				$list['unit2']=$v['unit_t_no'];
				$list['unit2_count']=$v['unit_t_count'];
				// $list['other_count']=$v['other_count'];
				$list['old_goods_id']=$v['goods_id'];
				$list['amount']=$list['declare_amount']=$v['goods_count']+$v['other_count'];//预计到货数量=采购箱数中小件商品总数量+散货数量

				$list['manual_id']=$v['manual_id'];
				$list['erp_code']=$value['list']['erp_code'];

				if(empty($v['goods_no'])){
					$trans->rollback();
					$return['status']=0;
					$return['info']="商品编码不能为空";
					$this->ajaxReturn($return);
				}
				if(empty($v['goods_name'])){
					$trans->rollback();
					$return['status']=0;
					$return['info']="商品名称不能为空";
					$this->ajaxReturn($return);
				}
				$list['goods_no']=$v['goods_no'];
				$list['goods_name']=$v['goods_name'];
				$list['price']=$v['goods_price'];
				$list['goods_spec']=$v['standard'];
				$list['source_no']=$v['pn'];
				$list['unit1']=$v['unit_no'];
				
				if($v['yc_count']){
					$list['cloud_depot_status']=1;
					$list['cloud_num']=$v['yc_count'];
					$list['cloud_unit']=$v['unit_no'];
				}
				$list['expected_time']=strtotime($v['expected_time']);
				$list['add_time']=time();
				
				//判断是否重复
				$map_old=[];
				$map_old['old_purchasing_no']=$value['list']['order_no'];
				$map_old['goods_no']=$v['goods_no'];
				$has_info=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->field('confirm_status')->where($map_old)->find();
				if($has_info){
					if($has_info['confirm_status']==2){
						$trans->rollback();
						$return['status']=0;
						$return['info']="已确认不能重复推送!";
						$this->ajaxReturn($return);
					}
					//覆盖原数据
					$list['receive_amount']=$list['amount'];
					unset($list['amount']);
					$status=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->where($map_old)->save($list);//到货通知单添加
					//echo M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql();
					file_put_contents('./log/arrivalOrder_sql.log',date('Y-m-d H:i:s').M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql().PHP_EOL,FILE_APPEND);//日志导出sql
					if($status!==false){
						continue;
					}else{
						// echo M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql();
						$trans->rollback();
						$return['status']=0;
						$return['info']="添加失败";
						$this->ajaxReturn($return);
					}
				}else{
					//新增
					$status=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->add($list);//到货通知单添加
					//echo M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql();
					file_put_contents('./log/arrivalOrder_sql.log',date('Y-m-d H:i:s').M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql().PHP_EOL,FILE_APPEND);//日志导出sql
					if($status){
						continue;
					}else{
						// echo M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql();
						$trans->rollback();
						$return['status']=0;
						$return['info']="添加失败";
						$this->ajaxReturn($return);
					}
				}
			}
		
			$trans->commit();
			$return['status']=1;
			$return['info']="添加成功";
			$this->ajaxReturn($return);
	}
	//到货通知单接口--接收
    public function arrivalOrder(){
		$country=M('Country',C('DB_PRS'),C('DB_DEPOT'));
		$trans=M('',C('DB_PRS'),C('DB_DEPOT'));
		$trans->startTrans();   // 开启事务
		$coin=M('Coin',C('DB_PRS'),C('DB_DEPOT'));
		$data=file_get_contents('php://input');
		file_put_contents('./log/arrivalOrder_data.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		// $data='[{"list":{"id":"13","order_no":"2017031412126301173","erp_code":"12","warehouse_code":"12345678"},"goods":[{"goods_id":"14","unit_t_goods_spec":"unit_t_goods_spec","unit_t_no":"021","unit_t_count":"12","other_count":"3","goods_no":"20170312202413813","goods_name":"fodd","manual_id":"0","goods_count":"44","expected_time":"2017-03-14","unit_no":"015","goods_price":"0.00","w_code":"30744775","hscode":"hdjkshdkjn"},{"goods_id":"15","unit_t_goods_spec":"unit_t_goods_spec","unit_t_no":"021","unit_t_count":"12","other_count":"3","goods_no":"20170312212758686","goods_name":"4444","manual_id":"0","goods_count":"44","expected_time":"2017-03-14","unit_no":"018","goods_price":"4.00","w_code":"30744775","hscode":"44444444"}]}]';
		$param=json_decode($data,true);

		foreach($param as $key=>$value){
			$warehouse_code=$value['list']['warehouse_code'];
			$this->db_config($warehouse_code);
			
			$t_no=$this->serialNumber_arrivalOrder('ArrivalOrder',$warehouse_code);//流水号
			$order_no='AO'.date('Ymd',time()).$t_no;//流水单号
			$batch_no='BAO'.date('YmdHis',time());//批次号
			
			$list=array();
			$list['order_no']=$order_no;
			$list['batch_no']=$batch_no;
			foreach($value['goods'] as $k => $v){
				$country_info=$country->where(array('country_name'=>$v['country']))->find();
				$coin_info=$coin->where(array('coin_name'=>$v['currency']))->find();
				
				$list['old_purchasing_no']=$value['list']['order_no'];
				$list['currency']=$coin_info['coin_code'];
				$list['bar_code']=$v['sn'];//条形码
				$list['old_goods_id']=$v['goods_id'];
				$list['country_code']=$country_info['country_code'];
				$list['unit2']=$v['unit_t_no'];
				$list['unit2_count']=$v['unit_t_count'];
				// $list['other_count']=$v['other_count'];
				$list['old_goods_id']=$v['goods_id'];
				$list['amount']=$list['declare_amount']=$v['goods_count']+$v['other_count'];//预计到货数量=采购箱数中小件商品总数量+散货数量

				$list['manual_id']=$v['manual_id'];
				$list['erp_code']=$value['list']['erp_code'];
				if(empty($v['goods_no'])){
					$trans->rollback();
					$return['status']=0;
					$return['info']="商品编码不能为空";
					$this->ajaxReturn($return);
				}
				if(empty($v['goods_name'])){
					$trans->rollback();
					$return['status']=0;
					$return['info']="商品名称不能为空";
					$this->ajaxReturn($return);
				}
				$list['goods_no']=$v['goods_no'];
				$list['goods_name']=$v['goods_name'];
				$list['price']=$v['goods_price'];
				$list['goods_spec']=$v['standard'];
				$list['source_no']=$v['pn'];
				$list['unit1']=$v['unit_no'];
				
				if($v['yc_count']){
					$list['cloud_depot_status']=1;
					$list['cloud_num']=$v['yc_count'];
					$list['cloud_unit']=$v['unit_no'];
				}
				$list['expected_time']=strtotime($v['expected_time']);
				$list['add_time']=time();
				$status=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->add($list);//到货通知单添加
				//echo M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql();

				file_put_contents('./log/arrivalOrder_sql.log',date('Y-m-d H:i:s').M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql().PHP_EOL,FILE_APPEND);//日志导出sql
				if($status){
					continue;
				}else{
					$trans->rollback();
					$return['status']=0;
					$return['info']="添加失败";
					$this->ajaxReturn($return);
				}
			}
		}
		$trans->commit();
		$return['status']=1;
		$return['info']="添加成功";
		$this->ajaxReturn($return);
	}
	//销售单价格修改--接收
    public function pushorder_price_edit(){
		$m = M('Pushorder',C('DB_PRS'),C('DB_DEPOT'));
		$n = M('Pushordergoods',C('DB_PRS'),C('DB_DEPOT'));
		
		$datas=file_get_contents('php://input');
		$param=json_decode($datas,true);
		$warehouse_code=$param['warehouse_code'];
		file_put_contents('./log/pushorder_price_edit.log',date('Y-m-d H:i:s').var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$this->db_config($warehouse_code);
		
		$list_info=$m->where(array('order_no'=>$param['order_no']))->find();
		$map['order_id']=$list_info['id'];
		$map['goods_no']=$param['goods_no'];
		$data['goods_price']=$param['goods_price'];
		// $map['erp_code']=$param['erp_code'];
		
		$info=$n->where($map)->find();
		if(!$info){
			$return['info'] = "对应仓库未找到对应订单信息";
			$return['status'] = 0;
			$this->ajaxReturn($return);
		}else{
			$res=$n->where($map)->save($data);
			//echo $m->getlastsql();
			//file_put_contents('./log/ss.log',date('Y-m-d H:i:s').var_export($m->getlastsql(),true).PHP_EOL,FILE_APPEND);//日志导出sql
			if($res!==false) {
				$return['info'] = "接收成功";
				$return['status'] = 1;
				$this->ajaxReturn($return);
			}
		}
	}
	//价格修改--接收
    public function price_edit(){
		$datas=file_get_contents('php://input');
		$param=json_decode($datas,true);

		$warehouse_code=$param['warehouse_code'];

		file_put_contents('./log/price_eidt.log',date('Y-m-d H:i:s').var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$this->db_config($warehouse_code);

		$map['old_goods_id']=$param['goods_id'];
		$data['price']=$param['price'];
		$map['erp_code']=$param['erp_code'];
		
		$m = M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		
		$info=$m->where($map)->find();
		if(!$info){
			$return['info'] = "未找到对应信息";
			$return['status'] = 0;
			$this->ajaxReturn($return);
		}else{
			$res=$m->where($map)->save($data);
			//echo $m->getlastsql();
			//file_put_contents('./log/ss.log',date('Y-m-d H:i:s').var_export($m->getlastsql(),true).PHP_EOL,FILE_APPEND);//日志导出sql
			if($res!==false) {
				$return['info'] = "接收成功";
				$return['status'] = 1;
				$this->ajaxReturn($return);
			}
		}
	}
	//到货通知单回执接口--接收
    public function realsend_confirm(){
		$datas=file_get_contents('php://input');
		$param=json_decode($datas,true);

		$warehouse_code=$param['warehouse_code'];

		// file_put_contents('./log/realsend_confirm.log',date('Y-m-d H:i:s').var_export($param,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$this->db_config($warehouse_code);
		$cate=I('cate');
		$sta=I('sta');
		if(!empty($cate) and $cate=='PRO'){
			$map['bound_cate_code']=I('cate');
		}
		if(!empty($sta)){
			$map['primarygoods_status']=I('sta');
		}
		$map['old_goods_id']=$param['goods_id'];
		$data['erp_receive_amount']=$param['count'];
		$map['erp_code']=$param['erp_code'];
		
		$m = M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$data['confirm_status']=1;
		$res=$m->where($map)->save($data);
		//echo $m->getlastsql();
		//file_put_contents('./ss.log',date('Y-m-d H:i:s').var_export($m->getlastsql(),true).PHP_EOL,FILE_APPEND);//日志导出sql
		
		if($res!==false) {
			$return['info'] = "接收成功";
			$return['status'] = 1;
			$this->ajaxReturn($return);
		}
	}
	//转换单入库(进到货通知)
	public function product_inbound(){
		$data=file_get_contents('php://input');
		file_put_contents('./log/product_inbound.log',date('Y-m-d H:i:s').var_export($data,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$param=json_decode($data,true);
		foreach($param as $key=>$value){
			$warehouse_code=$value['inbound_warehouse_code'];
			$this->db_config($warehouse_code);
			$country=M('Country',C('DB_PRS'),C('DB_DEPOT'));
			$coin=M('Coin',C('DB_PRS'),C('DB_DEPOT'));
			$t_no=$this->serialNumber_arrivalOrder('ArrivalOrder',$warehouse_code);//流水号
			$order_no='AO'.date('Ymd',time()).$t_no;//流水单号
			$batch_no='BAO'.date('YmdHis',time());//批次号
			
			$list=array();
			$list['order_no']=$order_no;
			$list['batch_no']=$batch_no;
			
			//主产品
			$coin_info=$coin->where(array('coin_name'=>$value['current_type']))->find();
			
			$list['old_purchasing_no']=$value['purchasing_no'];
			$list['currency']=$coin_info['coin_code'];
			$list['old_goods_id']=$value['id'];
			$list['country_code']='142';//中国
			$list['unit2']=$value['unit2'];
			$list['amount']=$list['declare_amount']=$value['pro_num'];//生产完成数量

			$list['manual_id']=$value['manua_id'];
			$list['erp_code']=$value['erp_code'];
			$list['goods_no']=$value['pro_no'];
			$list['goods_name']=$value['pro_name'];
			$list['price']=$value['inbound_price'];
			$list['goods_spec']=$value['pro_spec'];
			$list['source_no']=$value['source_no'];
			$list['unit1']=$value['unit1'];
			$list['bound_cate_code']='PRO';//入库类型（生产入库）
			$list['primarygoods_status']=1;//主产品属性（生产入库）
			$list['expected_time']=strtotime($value['overdue_time']);
			$list['add_time']=time();
			$status=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->add($list);//到货通知单添加
			//echo M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql();
			
			file_put_contents('./log/arrivalOrder_sql.log',date('Y-m-d H:i:s').M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql().PHP_EOL,FILE_APPEND);//日志导出sql
			if($status){
				//副产品
				foreach($value['byproduct_list'] as $k => $v){
					$coin_info=$coin->where(array('coin_name'=>$v['current_type']))->find();
					
					$list['old_purchasing_no']=$value['order_no'];
					$list['currency']=$coin_info['coin_code'];
					$list['old_goods_id']=$v['id'];
					$list['country_code']='142';
					$list['unit2']=$v['unit2'];
					$list['amount']=$list['declare_amount']=$v['pro_num'];//生产完成数量

					$list['manual_id']=$v['manua_id'];
					$list['erp_code']=$value['erp_code'];
					$list['goods_no']=$v['pro_no'];
					$list['goods_name']=$v['pro_name'];
					$list['price']=$v['inbound_price'];
					$list['goods_spec']=$v['pro_spec'];
					$list['source_no']=$v['source_no'];
					$list['unit1']=$v['unit1'];
					$list['bound_cate_code']='PRO';//入库类型（生产入库）
					$list['primarygoods_status']=2;//副产品属性（生产入库）
					
					$list['expected_time']=strtotime($v['overdue_time']);
					$list['add_time']=time();
					$status=M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->add($list);//到货通知单添加
					//echo M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql();
					
					file_put_contents('./log/arrivalOrder_sql.log',date('Y-m-d H:i:s').M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'))->getlastsql().PHP_EOL,FILE_APPEND);//日志导出sql
					if($status){
						continue;
					}else{
						$return['status']=0;
						$return['info']="添加失败";
						$this->ajaxReturn($return);
					}
				}
			}else{
				$return['status']=0;
				$return['info']="添加失败";
				$this->ajaxReturn($return);
			}
		}
		$return['status']=1;
		$return['info']="添加成功";
		$this->ajaxReturn($return);
	}
	//////erp最终确认数量--接收
	public function last_confirm_new(){
		$datas=html_entity_decode(I('data'));
		
		file_put_contents('./log/last_confirm_new.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		
		// $datas='data={"identity":{"sign":"18c995f55eea36031028a9de4637d8e9","timestamp":1536203704},"data":{"erp_code":82,"warehouse_code":"11330213","order_no":71}}';
		
		$tdata=json_decode($datas,true);

		$param=$tdata['data'];
		$warehouse_code=$param['warehouse_code'];
		$this->db_config($warehouse_code);

		
		$map['old_purchasing_no']=$param['order_no'];
		$map['erp_code']=$param['erp_code'];
		$m = M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$data['confirm_status']=2;
		$res=$m->where($map)->save($data);

		if($res!==false){
			$return['info'] = "成功";
			$return['status'] = 1;
			$this->ajaxReturn($return);
		}
	}
	//////erp最终确认数量--接收
	public function last_confirm(){
		$datas=file_get_contents('php://input');
		//file_put_contents('./log/sss.log',date('Y-m-d H:i:s').var_export($datas,true).PHP_EOL,FILE_APPEND);//日志导出sql
		$param=json_decode($datas,true);

		$warehouse_code=$param['warehouse_code'];
		$this->db_config($warehouse_code);
		$cate=I('cate');
		$sta=I('sta');
		if(!empty($cate) and $cate=='PRO'){
			$map['bound_cate_code']=I('cate');
		}
		if(!empty($sta)){
			$map['primarygoods_status']=I('sta');
		}
		
		$map['old_goods_id']=$param['goods_id'];
		$map['erp_code']=$param['erp_code'];
		$m = M('ArrivalOrder',C('DB_PRS'),C('DB_DEPOT'));
		$data['confirm_status']=2;
		$res=$m->where($map)->save($data);
		// echo $m->getlastsql();
		// die;
		if($res!==false){
			$return['info'] = "成功";
			$return['status'] = 1;
			$this->ajaxReturn($return);
		}

	}


	function push($url,$post_data){
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
		
		$output = curl_exec($ch);
		// dump($output);
		// die;
		curl_close($ch);
		return $output;
	}
	
	public  function send_curl($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //post传值数据
        curl_setopt($ch, CURLOPT_POST, 1);
        //post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('data'=>json_encode($data))));
        $output = curl_exec($ch);
		// dump($output);
		// die;
        curl_close($ch);
        return $output;
    }
	//流水号(到货通知)
	public function serialNumber_arrivalOrder($tablename,$warehouse_code){
		$this->db_config($warehouse_code);
		$m=M($tablename,C('DB_PRS'),C('DB_DEPOT'));
		//当日流水号生成
		$map['_string']="add_time-UNIX_TIMESTAMP(DATE(NOW()))>0 and add_time-UNIX_TIMESTAMP(DATE(NOW()))<86400";
		$list=$m->distinct(true)->field('order_no')->where($map)->select();//当天添加的采购单数
		$count=count($list);
		
		// dump(C());
		// echo $m->getlastsql();
		// die;
		$count=$count+1;
		$serial_number="";
		if($count<10){
			$serial_number='0000'.strval($count);
		}
		if($count>=10 and $count<100){
			$serial_number='000'.$count;
		}
		if($count>=100 and $count<1000){
			$serial_number='00'.$count;
		}
		if($count>=1000 and $count<10000){
			$serial_number='0'.$count;
		}
		return $serial_number;//流水序号
	}
	//流水号
	public function serialNumber($tablename,$warehouse_code){
		$this->db_config($warehouse_code);
		$m=M($tablename,C('DB_PRS'),C('DB_DEPOT'));
		//当日流水号生成
		$map['_string']="add_time-UNIX_TIMESTAMP(DATE(NOW()))>0 and add_time-UNIX_TIMESTAMP(DATE(NOW()))<86400";
		$count=$m->where($map)->count();//当天添加的采购单数
		// dump(C());
		// echo $m->getlastsql();
		// die;
		$count=$count+1;
		$serial_number="";
		if($count<10){
			$serial_number='0000'.strval($count);
		}
		if($count>=10 and $count<100){
			$serial_number='000'.$count;
		}
		if($count>=100 and $count<1000){
			$serial_number='00'.$count;
		}
		if($count>=1000 and $count<10000){
			$serial_number='0'.$count;
		}
		return $serial_number;//流水序号
	}
	/*
	 *获取数据库配置
     */
    public function db_config($warehouse_code){
		$start_word=substr($warehouse_code,0,1);
		if($start_word=='T' or $start_word=='t'){//虚拟仓
			$info=M('User')->where(array('warehouse_code'=>$warehouse_code))->find();//获取配置表中对应域名的id
			$ss=M('Warehouse')->getlastsql();
			file_put_contents('./log/db_config.log',date('Y-m-d H:i:s').var_export($ss,true).PHP_EOL,FILE_APPEND);//日志导出sql
			if($info){  //天众数据库库配置
				!empty($info['db_ip'])?$db_ip=$info['db_ip']:$db_ip=C('DEPOT_DB_HOST');
				!empty($info['db_name'])?$db_name=$info['db_name']:$db_name=C('DEPOT_DB_NAME');
				!empty($info['db_username'])?$db_username=$info['db_username']:$db_username=C('DEPOT_DB_USER');
				!empty($info['db_password'])?$db_password=$info['db_password']:$db_password=C('DEPOT_DB_PWD');
				!empty($info['db_port'])?$db_port=$info['db_port']:$db_port=C('DEPOT_DB_PORT');
				!empty($info['db_pre'])?$db_pre=$info['db_pre']:$db_pre=C('DEPOT_DB_PREFIX');

				$db_pre=C('ERP_DB_PREFIX');
				$db_name=$db_pre.$info['username'];
				//当前仓库数据库配置
				C('DB_DEPOT.DB_TYPE','mysql');
				C('DB_DEPOT.DB_HOST',$db_ip);
				C('DB_DEPOT.DB_NAME',$db_name);
				C('DB_DEPOT.DB_USER',$db_username);
				C('DB_DEPOT.DB_PWD',$db_password);
				C('DB_DEPOT.DB_PORT',$db_port);
				C('DB_PRS',$db_pre);
				C('DB_DEPOT.DB_CHARSET','utf8');
			}
		}else{
			$info=M('Warehouse')->where(array('warehouse_code'=>$warehouse_code))->find();//获取配置表中对应域名的id
			$ss=M('Warehouse')->getlastsql();
			file_put_contents('./log/db_config.log',date('Y-m-d H:i:s').var_export($ss,true).PHP_EOL,FILE_APPEND);//日志导出sql
			// echo M()->getlastsql();
			// dump($info);
			if($info){  //天众数据库库配置
				!empty($info['db_ip'])?$db_ip=$info['db_ip']:$db_ip=C('DEPOT_DB_HOST');
				!empty($info['db_name'])?$db_name=$info['db_name']:$db_name=C('DEPOT_DB_NAME');
				!empty($info['db_username'])?$db_username=$info['db_username']:$db_username=C('DEPOT_DB_USER');
				!empty($info['db_password'])?$db_password=$info['db_password']:$db_password=C('DEPOT_DB_PWD');
				!empty($info['db_port'])?$db_port=$info['db_port']:$db_port=C('DEPOT_DB_PORT');
				!empty($info['db_pre'])?$db_pre=$info['db_pre']:$db_pre=C('DEPOT_DB_PREFIX');
				
				//当前仓库数据库配置
				C('DB_DEPOT.DB_TYPE','mysql');
				C('DB_DEPOT.DB_HOST',$db_ip);
				C('DB_DEPOT.DB_NAME',$db_name);
				C('DB_DEPOT.DB_USER',$db_username);
				C('DB_DEPOT.DB_PWD',$db_password);
				C('DB_DEPOT.DB_PORT',$db_port);
				C('DB_PRS',$db_pre);
				C('DB_DEPOT.DB_CHARSET','utf8');
			}
			
			//加载自定义配置信息
			$m=M('Config',C('DB_PRS'),C('DB_DEPOT'));
			$list=$m->where(array('status'=>1))->getField('en_name,value');
			C('base_config',$list);
		}
    }
}